using System;
using System.IO;
using System.Text;

namespace TimeMachine.Engine.Vcs.Svn
{
	public class UnifiedDiffParser : IDiffParser
	{
		public void Parse(Func<TextReader> openReader, ProcessChangesParams processParams)
		{
			using(var reader = openReader())
			{
				var skipFile = false;
				string line;
				while((line = RobustReadLine(reader)) != null)
				{
					if(line.StartsWith("Index: "))
					{
						var filename = line.Substring("Index: ".Length).Trim();
						skipFile = !processParams.OnNextFile(filename);
					}
					else
					{
						if (skipFile) continue;
						if(line.StartsWith("@@")) processParams.OnNextChunk();
						else if(line.StartsWith("+++") || line.StartsWith("---")) continue;
						else if(line.StartsWith("-")) processParams.OnNextChange(new LineRemovedInfo(line.Substring(1)));
						else if(line.StartsWith("+")) processParams.OnNextChange(new LineAddedInfo(line.Substring(1)));
					}
				}
			}
		}

		private static string RobustReadLine(TextReader reader)
		{
			var sb = new StringBuilder(500);
			int ch = reader.Read();
			if(ch == -1) return null;
			while (ch != -1 && ch != '\r' && ch != '\n')
			{
				if(sb.Length < 500) sb.Append((char)ch);
				ch = reader.Read();
			}
			return sb.ToString();
		}
	}

	public interface IDiffParser
	{
		void Parse(Func<TextReader> openReader, ProcessChangesParams processParams);
	}
}